package com.exigen.training.services.impl;

import java.sql.SQLException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.exigen.training.UserEntity;
import com.exigen.training.dao.UserDAO;
import com.exigen.training.services.UserService;

public class UserServiceIMPL implements UserService, UserDetailsService {

	private UserDAO userDAO;

	@Override
	public boolean createUserIfNotExist(UserEntity userEntity) throws Exception {
		try {
			userDAO.save(userEntity);
		}

		catch (DataIntegrityViolationException e) {
			if (e.getRootCause() instanceof SQLException) {
				if (((SQLException) e.getRootCause()).getErrorCode() == 1) {
					throw new Exception("User exists!");
				}
			}
		}
		return false;
	}
	
	@Override
	public UserDetails loadUserByUsername(String arg0)
			throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		return null;
	}

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public UserEntity getUserByUserName(String userLogin) {
		return userDAO.getUserByUserName(userLogin);
	}
}
